//
//  ZoomImageView.m
//  Maldives
//
//  Created by luo danal on 6/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ZoomImageView.h"

@implementation ZoomImageView
@synthesize imageView = _imageView;
@synthesize image = _image;

- (void)dealloc{
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor blackColor];
        _imageView = [[WebImageView alloc] initWithFrame:self.bounds];
        _imageView.caches = YES;
        _imageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
        _imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self addSubview:_imageView];
        [_imageView release];
        
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.maximumZoomScale = 2.f;
        self.minimumZoomScale = 1.f;
        self.delegate = self;
        {
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
            g.numberOfTapsRequired = 1;
            [self addGestureRecognizer:g];
            [g release];
        }
        {
            UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
            g.numberOfTapsRequired = 2;
            [self addGestureRecognizer:g];
            [g release];
        }
        
    }
    return self;
}

- (void)setImage:(UIImage *)image{
    self.imageView.image = image;
    self.maximumZoomScale = MAX(2.f,MAX(image.size.width/self.bounds.size.width, image.size.height/self.bounds.size.height));
}

- (UIImage *)image{
    return self.imageView.image;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)setReceiver:(id)receiver singleTapSelector:(SEL)selector{
    _receiver = receiver;
    _singleTapSelector = selector;
}

- (void)doubleTap{
    [UIView animateWithDuration:.28f animations:^{
        self.zoomScale = self.zoomScale >= self.maximumZoomScale ? 1.f : 2.f*self.zoomScale;
    }];
}

- (void)singleTap{
    if (_receiver && _singleTapSelector) {
        [_receiver performSelector:_singleTapSelector withObject:nil afterDelay:.0f];
    }    
}

- (void)tap:(UITapGestureRecognizer *)g{
    if (g.numberOfTapsRequired == 2) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [self doubleTap];
    } else if (g.numberOfTapsRequired == 1){
        [self performSelector:@selector(singleTap) withObject:nil afterDelay:.28f];
    }
}
@end
